// 操作日志页面
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import useStore from '../../components/useStore';
import { Col, Empty, notification, Pagination, Row, Spin, Button, Tooltip, ConfigProvider } from 'antd';
import { CopyOutlined } from '@ant-design/icons';
import store from '../../untils/store';
import dayjs from 'dayjs';
import request from '../../untils/request';

// 蓝色主题配置
const blueTheme = {
  token: {
    colorPrimary: '#156ef3',
    colorText: '#333333',
    colorTextSecondary: '#666666',
  },
  components: {
    Table: {
      headerBg: '#f0f5ff',
    },
  },
};

const OperationLog = () => {
  const { collapsed } = useStore();
  const { user } = store();
  const [operationLogs, setOperationLogs] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);

  // 复制SQL语句到剪贴板
  const copyToClipboard = useCallback((text, index) => {
    navigator.clipboard.writeText(text).then(() => {
      notification.success({
        message: '复制成功',
        description: `第 ${index + 1} 条SQL语句已复制到剪贴板`,
        duration: 2
      });
    }).catch(() => {
      notification.error({
        message: '复制失败',
        description: '无法访问剪贴板，请手动复制',
        duration: 2
      });
    });
  }, []);

  // 获取操作日志数据
  const fetchOperationLogs = useCallback(async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const data = await request("/admin/operation/getOperationLog", {
        method: 'POST',
        mode: 'cors',
        body: {
          pageSize: size,
          offset: (page - 1) * size
        }
      });

      setOperationLogs(data.data || []);
      setTotal(data.total || 0);
      return true;
    } catch (error) {
      // 错误日志上报
      const errorLog = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        context: `用户ID: ${user?.id} 在获取操作日志时发生错误`
      };

      try {
        await request("/admin/error/insertErrorLog", {
          method: "POST",
          body: { error_log: errorLog }
        });
      } catch (err) {
        console.error("错误日志上报失败:", err);
      }

      notification.error({
        message: "数据加载失败",
        description: "获取操作日志时发生错误，请稍后重试",
        duration: 3
      });
      return false;
    } finally {
      setLoading(false);
    }
  }, [user]);

  // 处理分页和页大小变化
  const handlePageOrSizeChange = useCallback(async (page, size) => {
    setCurrentPage(page);
    setPageSize(size);
    await fetchOperationLogs(page, size);
  }, [fetchOperationLogs]);

  // 初始加载数据
  useEffect(() => {
    const init = async () => {
      await fetchOperationLogs(currentPage, pageSize);
    };
    init();
  }, [fetchOperationLogs, currentPage, pageSize]);

  // 格式化时间显示
  const formatTime = useCallback((timeStr) => {
    return dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss');
  }, []);

  // 计算表格列宽度
  const columnWidths = useMemo(() => {
    const baseWidth = collapsed ? 94 : 84;
    return {
      index: `${(baseWidth * 5) / 100}%`,    // 序号列
      userId: `${(baseWidth * 10) / 100}%`,  // 操作人ID列
      userAccount: `${(baseWidth * 10) / 100}%`, // 操作人账号列
      sql: `${(baseWidth * 55) / 100}%`,     // SQL语句列
      time: `${(baseWidth * 20) / 100}%`     // 时间列
    };
  }, [collapsed]);

  return (
    <ConfigProvider theme={blueTheme}>
      <div style={{
        height: "94%",
        backgroundColor: '#F1F1F1',
        right: "1%",
        top: "6vh",
        overflow: "hidden",
        width: collapsed ? "94%" : "84%",
        position: "absolute",
        fontSize: "0.8rem",
        color: "#333",
        transition: "width 0.3s ease"
      }}>
        <div style={styles.container}>
          <div style={styles.contentWrapper}>
            <div style={styles.tableContainer}>
              {/* 固定表头 */}
              <div style={styles.tableHeader}>
                <Row style={styles.headerRow}>
                  <Col style={{ ...styles.headerCell, width: columnWidths.index }}>序号</Col>
                  <Col style={{ ...styles.headerCell, width: columnWidths.userId }}>操作人ID</Col>
                  <Col style={{ ...styles.headerCell, width: columnWidths.userAccount }}>操作人账号</Col>
                  <Col style={{ ...styles.headerCell, width: columnWidths.sql }}>SQL/操作</Col>
                  <Col style={{ ...styles.headerCell, width: columnWidths.time }}>操作时间</Col>
                </Row>
              </div>

              {/* 表格内容区域 */}
              <div style={styles.tableBody}>
                <Spin spinning={loading} tip="加载中...">
                  {operationLogs.length === 0 ? (
                    <div style={styles.emptyState}>
                      <Empty description="暂无操作日志记录" />
                    </div>
                  ) : (
                    operationLogs.map((item, index) => {
                      const globalIndex = (currentPage - 1) * pageSize + index + 1;
                      
                      return (
                        <Row
                          key={index}
                          style={{
                            ...styles.dataRow,
                            backgroundColor: index % 2 === 0 ? '#f9fafb' : '#ffffff',
                          }}
                          onMouseEnter={(e) => e.currentTarget.style.backgroundColor = '#e6f7ff'}
                          onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 
                            index % 2 === 0 ? '#f9fafb' : '#ffffff'}
                        >
                          <Col style={{ ...styles.dataCell, width: columnWidths.index }}>
                            {globalIndex}
                          </Col>
                          <Col style={{ ...styles.dataCell, width: columnWidths.userId }}>
                            <div style={styles.textContainer} title={item.user_id || '-'}>
                              {item.user_id || '-'}
                            </div>
                          </Col>
                          <Col style={{ ...styles.dataCell, width: columnWidths.userAccount }}>
                            <div style={styles.textContainer} title={item.user_account || '-'}>
                              {item.user_account || '-'}
                            </div>
                          </Col>
                          <Col style={{ ...styles.dataCell, width: columnWidths.sql, position: 'relative' }}>
                            {/* SQL内容区域 - 右侧预留按钮空间 */}
                            <div style={styles.sqlContent} title={item.sql_words || '无SQL语句'}>
                              {item.sql_words || '无SQL语句'}
                            </div>
                            
                            {/* 复制按钮 - 右侧悬浮，不遮挡内容 */}
                            <Tooltip title="复制SQL">
                              <Button
                                icon={<CopyOutlined />}
                                size="small"
                                onClick={() => copyToClipboard(item.sql_words || '', index)}
                                style={styles.copyButton}
                              />
                            </Tooltip>
                          </Col>
                          <Col style={{ ...styles.dataCell, width: columnWidths.time }}>
                            <div style={styles.textContainer} title={formatTime(item.time) || '-'}>
                              {formatTime(item.time) || '-'}
                            </div>
                          </Col>
                        </Row>
                      );
                    })
                  )}
                </Spin>
              </div>

              {/* 分页控件 */}
              <div style={styles.paginationContainer}>
                <Pagination
                  current={currentPage}
                  pageSize={pageSize}
                  onChange={handlePageOrSizeChange}
                  onShowSizeChange={handlePageOrSizeChange}
                  total={total}
                  showSizeChanger
                  showQuickJumper
                  showTotal={(total) => `共 ${total} 条记录`}
                  pageSizeOptions={['10', '20', '50', '100']}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </ConfigProvider>
  );
};

// 优化的样式 - 重点解决文本换行问题
const styles = {
  container: {
    width: "100%",
    height: "100%",
    position: "relative",
    backgroundColor: "#F1F1F1",
    color: "#333333"
  },
  contentWrapper: {
    width: "98%",
    height: "95%",
    margin: "1%",
    backgroundColor: "white",
    borderRadius: "8px",
    boxShadow: "0 2px 8px rgba(0, 0, 0, 0.06)",
    overflow: "hidden"
  },
  tableContainer: {
    width: "100%",
    height: "100%",
    display: "flex",
    flexDirection: "column"
  },
  tableHeader: {
    flexShrink: 0,
    borderBottom: "1px solid #e8e8e8"
  },
  headerRow: {
    width: "100%",
    backgroundColor: "#f0f5ff",
    color: "#156ef3",
    fontWeight: "500"
  },
  headerCell: {
    padding: "12px 8px",
    textAlign: "left",
    borderRight: "1px solid #e8e8e8",
    whiteSpace: "nowrap",
    fontSize: "0.8rem"
  },
  tableBody: {
    flexGrow: 1,
    overflowY: "auto",
    overflowX: "hidden"
  },
  dataRow: {
    width: "100%",
    transition: "background-color 0.2s",
    borderBottom: "1px solid #e8e8e8"
  },
  dataCell: {
    padding: "12px 8px",
    textAlign: "left",
    fontSize: "0.8rem",
    color: "#333333"
  },
  // 通用文本容器样式 - 解决换行问题
  textContainer: {
    width: "100%",
    wordBreak: "break-all",      // 允许在单词内换行
    whiteSpace: "normal",        // 正常换行
    overflow: "hidden",          // 隐藏溢出内容
    lineHeight: "1.6",           // 增加行高，提高可读性
  },
  // SQL内容特殊样式
  sqlContent: {
    width: "calc(100% - 40px)",  // 为复制按钮预留空间
    padding: "4px 0",
    fontSize: "0.75rem",
    lineHeight: "1.6",
    color: "#333333",
    wordBreak: "break-all",      // 强制长SQL语句换行
    whiteSpace: "normal",        // 允许正常换行
    overflow: "hidden",          // 防止内容溢出
  },
  copyButton: {
    position: "absolute",
    top: "12px",
    right: "8px",
    height: "24px",
    padding: "0 6px",
    fontSize: "0.7rem"
  },
  paginationContainer: {
    flexShrink: 0,
    padding: "16px",
    textAlign: "right",
    borderTop: "1px solid #e8e8e8",
    backgroundColor: "#fff"
  },
  emptyState: {
    padding: "50px 0",
    textAlign: "center",
    color: "#666"
  }
};

export default React.memo(OperationLog);
